# -*- coding: utf-8 -*-
# @Date   : 2020/01/07
# @File   : IC_Past1YearCreCardQueryInsCnt_ZBC.py
# @Author : yanhaopeng

'''eof
name:借款人近1年信用卡审批查询机构数
code:IC_Past1YearCreCardQueryInsCnt_ZBC
tableName:
columnName:
groups:征信模块-准入策略
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
阈值 = [当前查询日期 - 360天, 当前查询日期]
FACTOR = 查询记录(POQ)--查询记录信息单元(PH01)中查询日期(PH010R01)属于阈值，
		且查询原因(PH010Q03)为"03"（信用卡审批）的法人机构数(查询机构(PH010Q02)去重计数)
'''

import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None or table == "":
            return [{}]
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return [{}]
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def IC_Past1YearCreCardQueryInsCnt():
    data = IC_DSJ_2D['data']
    # 查询记录   [1..1]
    POQ = getTable(data, 'POQ', 1)
    factor = []
    query_Ins = []
    if POQ is None:
        return u'缺失值'
    elif POQ == [{}]:
        return 0
    else:
        # 查询记录信息单元   [0..*]
        PH01 = getTable(POQ[0], 'PH01', 0)
        if PH01 is None:
            return u'缺失值'
        elif PH01 == [{}]:
            return 0
        else:
            for i in PH01:
                try:
                    # 查询日期   [1..1]
                    PH010R01 = i.get('PH010R01')
                    # 查询原因   [1..1]
                    PH010Q03 = i.get('PH010Q03')
                    # 查询机构   [1..1]  
                    PH010Q02 = i.get('PH010Q02')
                    if PH010R01 in null_type_list or PH010Q03 in null_type_list or PH010Q02 in null_type_list:
                        factor.append(None)
                    else:
                        now = datetime.datetime.now()
                        oneyear = datetime.timedelta(days=12 * 30)
                        query_date = (now - oneyear).strftime('%Y-%m-%d')
                        # 03-信用卡审批
                        if PH010R01 > query_date and PH010Q03 == '03':
                            if PH010Q02 not in query_Ins:
                                factor.append(1)
                                query_Ins.append(PH010Q02)
                            else:
                                factor.append(0)
                        else:
                            factor.append(0)
                except:
                    factor.append(None)
                    continue

    factor = filter(lambda x: x is not None, factor)
    if len(factor) == 0:
        return u'缺失值'
    else:
        return len(query_Ins)


result = IC_Past1YearCreCardQueryInsCnt()


# import json
# ratingRequest = {"legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511", "creditCode": "123456",
#                  "regNumber": "12345", "relativeDate":u'2019/08/09'}
# with open('F:/hp/IC_DSJ1.json', 'r') as f:
#     IC_DSJ_2D = json.loads(f.read())['IC_DSJ']
# print IC_Past1YearCreCardQueryInsCnt()
